package com.qf.controller;

import com.qf.model.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.CodeUtil;
import com.qf.util.EmailUtils;
import com.qf.util.MD5Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/login")
public class LoginController extends BaseServlet {

    UserService service=new UserServiceImpl();

    public String activate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String code = request.getParameter("c");
        //update t_user set status=1 where code=code
        //int a=service.active(code);
        int a=1;
        if(a==1){
            return "REDIRECT:login.jsp";
        }else{
            request.setAttribute("message","激活失败");
            return "FORWARD:error.jsp";
        }
    }

    /**
     * 这是一个注册的方法
     * @param request
     * @param response
     */
    public String userRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * username: 12312
         * password: 123
         * repassword: 123
         * email: 12312@qq.com
         * sex: 男
         */
        String username = request.getParameter("username");
        if(username==null){
            request.setAttribute("message","用户名不能为空");
            return "FORWARD:error.jsp";
        }
        String password = request.getParameter("password");
        if(password==null||password.length()>6){
            request.setAttribute("message","密码不能超过六位和不能为null");
            return "FORWARD:error.jsp";
        }
        String repassword = request.getParameter("repassword");
        if(!repassword.equals(password)){
            request.setAttribute("message","两次密码输入不一致");
            return "FORWARD:error.jsp";
        }


        String email = request.getParameter("email");
        Integer sex = Integer.parseInt(request.getParameter("sex"));
        //此时要注意，在数据库中密码不能明文存储，所以我们涉及到加密
        //注册和登录的时候必须是相同的加密算法
        //123456==>dsajhdksahdsahlhj
        //加密：可逆加密和不可逆加密，rsa
        //常用的不可逆加密：MD5;
        //SHA家族
        //加密手段上：
            //盐值加密==>你要知道盐是什么
            //迭代加密

        password= MD5Utils.stringToMD5(password+username);
        String code= CodeUtil.getCode();
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setCode(code);
        user.setEmail(email);
        user.setRole(1);
        user.setSex(sex);

        int register = service.register(user);
        if(register==1){
            //注册成功之后，需要发送邮件给用户进行激活
            //update t_user set status=1 where code=code

            EmailUtils.sendEmail(user);
            //response.sendRedirect("registerSuccess.jsp");
            return "REDIRECT:registerSuccess.jsp";
        }else{
            request.setAttribute("message","注册失败");

            return "FORWARD:error.jsp";
        }


        //int a=service.register(user);



    }

    //检查用户名不存在的方法
    public String checkUsername(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        int i = service.checkUsername(username);
        /*response.getWriter().print(i);*/
        return String.valueOf(i);
    }


    public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        if(username==null){
            request.setAttribute("message","用户名不能为空");
            return "FORWARD:error.jsp";
        }
        String password = request.getParameter("password");
        if(password==null||password.length()>6){
            request.setAttribute("message","密码不能超过六位和不能为null");
            return "FORWARD:error.jsp";
        }
        String code = request.getParameter("code");
        String code1="";
        Cookie[] cookies = request.getCookies();
        for(Cookie c:cookies){
            if("code".equals(c.getName())){
                code1=c.getValue();
            }
        }
        if(!code.equalsIgnoreCase(code1)){
            request.setAttribute("message","验证码输入不正确");
            return "FORWARD:error.jsp";
        }

        //实现记住我操作
        if(request.getParameter("auto")!=null){

            Cookie c=new Cookie("username",username);
            Cookie c1=new Cookie("password",password);
            c.setMaxAge(14*24*60*60);
            c1.setMaxAge(14*24*60*60);
            response.addCookie(c);
            response.addCookie(c1);
        }else{
            Cookie[] cookies1 = request.getCookies();
            for(Cookie c:cookies1){
                if("username".equals(c.getName())){
                    c.setMaxAge(0);
                    response.addCookie(c);
                }
                if("password".equals(c.getName())){
                    c.setMaxAge(0);
                    response.addCookie(c);
                }
            }
        }

        //登录是不是忘了加密
        password=MD5Utils.stringToMD5(password+username);
    //select * from t_user where username=? and password=?
    //User u=service.login(username,password);
        User u=new User();
        u.setId(1);
        u.setUsername("zhangsan");
        u.setRole(1);
        if(u!=null){
            request.getSession().setAttribute("loginUser",u);
            //分析了index.jsp中的数据来源，在head.jsp中，数据不是转发过来的，是发ajax请求拿到的
           return "REDIRECT:index.jsp";

        }else{
            request.setAttribute("message","登录失败");
            return "FORWARD:error.jsp";
        }



    }

    public String logOut(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //清空session
        request.getSession().invalidate();

        return "FORWARD:login.jsp";
    }



}
